package com.chenshu.mycnblog.controller;

import com.chenshu.mycnblog.common.Constant;
import com.chenshu.mycnblog.common.MyResponse;
import com.chenshu.mycnblog.common.SessionUtil;
import com.chenshu.mycnblog.model.UserInfo;
import com.chenshu.mycnblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA
 * Description：user控制器层
 * User：chenshu
 * Date：2024-01-02
 * Time：11:31
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     *
     * @return 为空返回-1，成功添加返回1
     */
    @RequestMapping("/reg")
    public Object reg(UserInfo userInfo) {
        // 1.非空校验
        if (!StringUtils.hasLength(userInfo.getUsername()) ||
                !StringUtils.hasLength(userInfo.getPassword()) ||
                !StringUtils.hasLength(userInfo.getNickname())) {
            return MyResponse.fail(-1, "非法的参数请求");
        }
        // 2.进行添加操作
        int result = userService.registry(userInfo);
        if (result == 1) {
            return MyResponse.success("添加成功！", 1);
        } else {
            return MyResponse.fail(-1, "数据库添加错误！");
        }
    }

    /**
     *
     * @return 用户和密码都正确返回1，账号密码为空返回0，账号密码错误返回-1
     */
    @RequestMapping("/login")
    public int login(HttpServletRequest request, String username, String password) {
        // 1.非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }
        // 2.验证账号密码，并存入session
        return userService.login(request, username, password);
    }

    /**
     *
     * @return 返回1代表登录，返回0代表未登录
     */
    @RequestMapping("/userstatus")
    public Integer getUserStatus(HttpServletRequest request) {
        if (SessionUtil.getLoginUser(request) > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public boolean logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        //移除用户
        session.removeAttribute(Constant.SESSION_USERINFO_KEY);
        return true;
    }

    @RequestMapping("/myinfo")
    public UserInfo getMyUserInfo(HttpServletRequest request) {
        int id = SessionUtil.getLoginUser(request);
        return userService.getUserInfo(id);
    }

    @RequestMapping("/userinfo")
    public UserInfo getUserInfo(Integer uid) {
        return userService.getUserInfo(uid);
    }
}
